package com.taylor.community.actuator;

import com.taylor.community.util.CommunityUtil;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


/**
 * 自定义端点 查看数据库连接是否正常
 */
@Component
@Endpoint(id = "database")
public class DatabaseEndpoint {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);
    @Autowired
    private DataSource dataSource;
    @ReadOperation//表示这个方法通过get请求来访问
    public String checkConnection(){
        //在try的小括号里面初始化的资源 编译时会自动加final 自动关闭资源
        try   (Connection con = dataSource.getConnection();)
        {
            return CommunityUtil.getJSONString(200,"获取连接成功!");

        } catch (SQLException se) {
            logger.error("获取连接失败："+se.getMessage());
            return CommunityUtil.getJSONString(500,"获取连接失败!");
        }
    }
}
